<?php

declare(strict_types=1);

namespace App\Fastapp\Model;

use Hyperf\DbConnection\Db;
use Mine\MineModel;

/**
 * @property int $id 主键
 * @property int $user_id 用户id
 * @property string $event 事件
 * @property string $date 活跃绝对日期
 * @property int $relative_day 活跃相对天数
 * @property int $total_day 累计活跃天数
 */
class AccountEventLog extends MineModel
{
    public bool $timestamps = false;
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'account_event_log';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'user_id', 'event', 'date', 'relative_day', 'total_day'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'user_id' => 'integer', 'relative_day' => 'integer', 'total_day' => 'integer'];

    public static function dailyActive(int $user_id, string $event, string $date = ''): void
    {
        if (!$date) $date = date('Y-m-d');
        $d = get_user_cache('e:' . $event, $user_id);
        if ($d == $date) return;
        set_user_cache(['e:' . $event => $date], $user_id);
        Db::select("INSERT INTO account_event_log (user_id, event, `date`, relative_day,total_day)
SELECT 
    u.gene_id,
    '$event',
    '$date' AS `date`,
    DATEDIFF('$date', u.created_at) AS relative_day,
    IFNULL((
        SELECT COUNT(DISTINCT da.date) + 1
        FROM account_event_log da
        WHERE da.user_id = u.gene_id and da.event='$event'
    ), 1) AS total_day
FROM 
    account u
WHERE 
    u.gene_id = $user_id;");
    }
}
